<template>
    <div class="tiktok_container">
        <el-affix v-if="tableTotal == 1" :offset="0">
            <div class="topheader">
                <div class="containerleft">
                    <img
                        style="width: 20px; height: 20px"
                        src="/static/err_tips.png"
                        alt="" />企业号授权到期后，客易达将无法收到来自该企业号的所有数据，请及时延长授权天数！<span
                        @click="dontRemind"
                        >不再提醒</span
                    >
                </div>
                <div class="ionic" @click="closedel">
                    <el-icon><Close /></el-icon>
                </div>
            </div>
        </el-affix>
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @selection-change="onSelectionChange"
            @select-all="onSelectAll">
            <template #headerOperate>
                <el-button type="primary" @click="bindfirm(1)">绑定企业号</el-button>
            </template>
        </ZwTable>
    </div>
    <!-- 确认弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
    <!-- 绑定企业号 -->
    <DiglogTiltok ref="DiglogTiltokRef" :totalfrim="totalfrim.basic" />
</template>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import {
    getDouyinList,
    getDouyinInfo,
    getRedConfig,
    getDouyinAuth,
    getDouyinCallback,
    getNoRemind,
    getDelAuth
} from '@/api/channelconfig/tiltok';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { AccreditColor, DOWLOAD_FILE } from '@/utils/smartMarketing';
import { useStore } from '@/store';
import DiglogTiltok from './components/DiglogTiltok.vue';
import { tableH, reSize } from '@/utils/utils';
import { Close } from '@element-plus/icons-vue';
const tabH = ref('500px');
const store = useStore();
const DeletdialogRef: any = ref(null);
const DiglogTiltokRef: any = ref(null);
const totalfrim: any = ref({
    basic: {
        bind_num: '' //企业号个数
    }
});
const tableTotal = ref(); //1-开启 2-关闭
const router = useRouter();
const GroupingRef: any = ref(null);
const isShow = ref(0);
const checkList = ref([]);
const delId = ref([]);
const defaultParams = {
    status: -1 //全部：-1 正常运行：1 授权失效：2 授权取消：3
};

const tableRef = ref<HTMLElement | null>(null);
// const tableRef = (ref < HTMLElement) | (null > null)
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '企业号名称',
            name: 'keywords',
            value: '',
            type: 'input',
            placeholder: '请输入企业号名称'
        },
        {
            label: '状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: -1 },
                            { name: '正常运行 ', id: 1 },
                            { name: '授权失败', id: 2 },
                            { name: '授权取消', id: 3 }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...v };
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams) };
};

const onBtn = (row: any) => {
    // <ElButton
    //   size="small"
    //   onClick={() => {
    //     delId.value = row.id
    //     onChange(1)
    //   }}
    // >
    //   延长授权
    // </ElButton>
    switch (row.status_name) {
        case '正常运行': // 正常运行
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            delId.value = row.id;
                            bindfirm(2);
                        }}>
                        重新授权
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            delId.value = row.id;
                            onChange(3);
                        }}>
                        取消授权
                    </ElButton>
                </>
            );
        case '授权失效': // 授权失效
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            delId.value = row.id;
                            bindfirm(2);
                        }}>
                        重新授权
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            delId.value = row.id;
                            onChange(3);
                        }}>
                        取消授权
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            delId.value = row.id;
                            onChange(4);
                        }}>
                        删除
                    </ElButton>
                </>
            );
        case '授权取消':
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            delId.value = row.id;
                            bindfirm(2);
                        }}>
                        重新授权
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={async () => {
                            delId.value = row.id;
                            onChange(4);
                        }}>
                        删除
                    </ElButton>
                </>
            );
    }
};
// 表格
const tableOption = [
    {
        prop: 'title',
        label: '企业号信息',
        width: 500,
        render({ row, column, index }) {
            return (
                <div class="table_cell">
                    <ElImage src={row.avatar} style="width: 36px; height: 36px;" />
                    <span> {row.nickname}</span>
                    <span>({row.e_account_role})</span>
                </div>
            );
        }
    },
    {
        prop: 'activity_status',
        label: '状态',
        minWidth: 100,
        render({ row, column, index }) {
            return (
                <span style={AccreditColor(row.status_name, 'obj')?.color}>
                    {AccreditColor(row.status_name, 'obj')?.name}
                </span>
            );
        }
    },
    {
        prop: 'activity_status',
        label: '剩余授权天数',
        minWidth: 150,
        render({ row, column, index }) {
            return <span>{row.status == 3 ? '--' : row.remain_auth_days + '天'}</span>;
        }
    },
    {
        prop: 'created_at',
        label: '绑定时间',
        width: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    getTableH();
    return getDouyinList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 导出表格数据
const exportTableData = () => {};
const onChange = (num: number) => {
    //1延长授权3取消授权。4删除
    switch (num) {
        case 1:
            DeletdialogRef.value.appDialog.title = '延长授权提醒';
            DeletdialogRef.value.content = '正在延长授权，点击确定后更新授权时长！';
            break;
        case 3:
            DeletdialogRef.value.appDialog.title = '取消授权提醒';
            DeletdialogRef.value.content = '取消授权后，客易达将收不到任何该企业号的数据，请慎重考虑！';
            break;
        case 4:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '删除后，客易达将收不到任何该企业号的数据，请慎重考虑！';
            break;
    }
    isShow.value = num;
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    const params = delId.value;
    switch (
        isShow.value //1延长授权3取消授权。4删除
    ) {
        case 1:
            await getDouyinAuth({ id: params, handle_type: 1 });
            ElMessage.success('延长授权成功');
            delId.value = [];
            checkList.value = [];
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 3:
            await getDouyinAuth({ id: params, handle_type: 2 });
            ElMessage.success('取消授权成功');
            delId.value = [];
            checkList.value = [];
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 4:
            await getDelAuth({ id: params });
            ElMessage.success('删除成功');
            delId.value = [];
            checkList.value = [];
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
    }
};

// 绑定企业号
const bindfirm = async (num: number) => {
    const params = delId.value;
    const res = await getDouyinInfo({});
    //is_limit企业号是否受限 0-未添加抖音应用 1-未受限 2-已达上限
    if (res.is_limit == 2) {
        totalfrim.value.basic = res;
        isShow.value = num;
        DiglogTiltokRef.value.appDialog.visible = true;
    } else if (res.is_limit == 1) {
        const auth_url = res.auth_url;
        switch (num) {
            case 1:
                window.open(auth_url);
                break;
            case 2:
                // eslint-disable-next-line no-case-declarations
                const res = await getDouyinAuth({ id: params, handle_type: 3 });
                delId.value = [];
                checkList.value = [];
                window.open(res.link);
                tableRef.value.reload();
                break;
        }
    } else {
        ElMessage.success(res.message);
    }
};
// 不再提醒是否开启
const getRedConfigList = async () => {
    const res = await getRedConfig({});
    tableTotal.value = res.status; //1-开启 2-关闭
};
//不在提醒确认按钮
const dontRemind = async () => {
    const res = await getNoRemind({});
    tableTotal.value = 2;
};
const closedel = () => {
    tableTotal.value = 2;
};

// 表格的自适应高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
onMounted(() => {
    reSize(getTableH);
    getRedConfigList();
});
</script>

<style lang="scss" scoped>
.tiktok_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

:deep(.table_cell) {
    display: flex;
    align-items: center;

    span {
        margin-left: 10px;
    }
}

:deep(.el-affix) {
    position: relative;
    top: -20px;
    width: 100%;

    .topheader {
        height: 40px;
        line-height: 40px;
        background: #fffbe6;
        border-radius: 2px;
        border: 1px solid #ffe58f;
        display: flex;
        align-items: center;
        padding: 0 10px;
        font-size: 14px;
        color: #000;
        justify-content: space-between;

        .containerleft {
            display: flex;
            align-items: center;
        }

        span {
            color: #ff6b00;
            cursor: pointer;
        }

        img {
            margin: 0 10px;
        }

        .ionic {
            cursor: pointer;
            display: flex;
        }
    }
}
</style>
